// src/plugins/runtimeSvgIconsPlugin.js

import { listSvgIcons } from "@/api/system/svgicons.js";

export default {
    async install(app, options = {}) {
        const { cacheKey = 'svgSprite', autoLoad = true } = options;

        const convertSvgToSymbol = (svgString, symbolId) => {
            svgString = svgString.replace(/<\?xml.*?\?>/g, '').replace(/<!DOCTYPE[^>]*>/g, '');
            const parser = new DOMParser();
            const doc = parser.parseFromString(svgString, 'image/svg+xml');
            const svgEl = doc.documentElement;
            const viewBox = svgEl.getAttribute('viewBox') || '0 0 1024 1024';
            const symbol = document.createElementNS('http://www.w3.org/2000/svg', 'symbol');
            symbol.setAttribute('id', symbolId);
            symbol.setAttribute('viewBox', viewBox);
            while (svgEl.firstChild) {
                symbol.appendChild(svgEl.firstChild);
            }
            return symbol.outerHTML;
        };

        const injectSprite = (sprite) => {
            if (document.getElementById('svg-sprite-container')) return;
            const container = document.createElement('div');
            container.style.display = 'none';
            container.id = 'svg-sprite-container';
            container.innerHTML = sprite;
            document.body.insertBefore(container, document.body.firstChild);
        };

        const loadSvgIcons = async () => {
            let sprite;  //= localStorage.getItem(cacheKey);
            // if (sprite) {
            //     injectSprite(sprite);
            //     return;
            // }
            try {
                const res = await listSvgIcons({});
                const svgData = res.result; // 数组，每项包含 iconName 和 svgCode
                let symbols = '';
                const exportedIcons = {};
                svgData.forEach(icon => {
                    const symbolId = `customize-${icon.iconName}`;
                    symbols += convertSvgToSymbol(icon.svgCode, symbolId);
                    exportedIcons[icon.iconName] = symbolId;
                });
                sprite = `<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">${symbols}</svg>`;
                // localStorage.setItem(cacheKey, sprite);
                injectSprite(sprite);
                app.config.globalProperties.$svgIcons = exportedIcons;
            } catch (error) {
                console.error('加载所有 SVG 图标失败:', error);
            }
        };

        if (autoLoad) {
            await loadSvgIcons();
        }

        app.config.globalProperties.$reloadSvgIcons = loadSvgIcons;
    }
};
